package com.androidhuman.example.mapsv2example;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.androidhuman.example.mapsv2example.R.drawable;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.internal.ic;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapActivity extends FragmentActivity {

	String[][] reports_info;
	SharedPreferences userPrefs;
	SharedPreferences.Editor userPrefsEditor;

	GoogleMap mGoogleMap; // 구글맵 객체
	LatLng startingPoint; // 맨 처음 보여줄 위도,경도 값 객체
	int startingScale = 7;
	float zoom1; // 현재 줌 레벨 (스케일)
	float zoom2; // 바뀐 줌 레벨 (스케일) // 뒤로가기 버튼으로 종료시 사용 (다시 사용될일 없음)
	public static Context MainContext;

	float mylatitude;
	float mylongitude;

	Point[] screenPointForLocation = new Point[4];

	// ///////////////////////////////////////////////////

	View btn_map; // 지도 모양 버튼 (뉴스피드 화면에서 등장한다)
	View banner_remove; // 현수막 안보이게 하는 버튼(삼각형)
	View popup_me;
	View gomylocation;

	FrameLayout bannerlayout;
	LinearLayout menu_more; // 액션바 아이콘 클릭하면 추가로 나오는 메뉴 레이아웃
	LinearLayout btn_make_event;
	LinearLayout btn_make_banner;
	LinearLayout gotoplace_select;

	LinearLayout place_ex1;
	LinearLayout place_ex2;

	View getfrommap;
	View gotoplace;

	int option_near_or_all = 1;

	int if_click = 0;
	

	// //////////////////////////////////////////////// 뉴스피드의 custom listview 구현

	int checkActionBar = 1; // 메뉴가 추가로 생성된 상태인지 확인 (다시 사용될일 없음)

	// ///////////////////////////////////////////////////////////////////////

	static double[][] location = new double[4][2];

	@SuppressLint("CommitPrefEdits")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		userPrefs = getSharedPreferences("USER", MODE_PRIVATE);
		userPrefsEditor = userPrefs.edit();
		setContentView(R.layout.activity_map);

		btn_make_event = (LinearLayout) findViewById(R.id.btn_make_event);
		btn_make_banner = (LinearLayout) findViewById(R.id.btn_make_banner);

		gotoplace_select = (LinearLayout) findViewById(R.id.gotoplace_select);
		gotoplace = (View) findViewById(R.id.gotoplace);

		place_ex1 = (LinearLayout) findViewById(R.id.place_ex1);
		place_ex2 = (LinearLayout) findViewById(R.id.place_ex2);

		Intent intent = getIntent();
		option_near_or_all = intent.getIntExtra("option_near_or_all", 2);

		mGoogleMap = ((SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map)).getMap();

		int height = getWindowManager().getDefaultDisplay().getHeight();
		int width = getWindowManager().getDefaultDisplay().getHeight();

		screenPointForLocation[0] = new Point(0, 0);
		screenPointForLocation[1] = new Point(width, 0);
		screenPointForLocation[2] = new Point(width, height);
		screenPointForLocation[3] = new Point(0, height);

		mylatitude = userPrefs.getFloat("mylatitude", 36);
		mylongitude = userPrefs.getFloat("mylongitude", 127);
		
		

		getfrommap = (View) findViewById(R.id.getfrommap);
		// ////////////////////////////////////////////////////////////(처음화면
		// 구글맵)

		if (option_near_or_all == 0) {

			startingPoint = new LatLng(mylatitude, mylongitude);
			startingScale = 14;
			// 초기화면
		} else {
			startingPoint = new LatLng(36.5, 127.8); // 초기 위도 경도 값
			startingScale = 7;

		}

		mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(startingPoint,
				startingScale));

		mGoogleMap.setMapType(0x00000001); // 구글맵 속성 지정

		mGoogleMap.setMyLocationEnabled(true);

		mGoogleMap.getUiSettings().setRotateGesturesEnabled(false);

		mGoogleMap.getUiSettings().setZoomControlsEnabled(false);
		mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);

		if (zoom2 < 8) {

			MarkCity();

		}

		zoom1 = mGoogleMap.getCameraPosition().zoom;

		// /////////////////////////////////////////////////// (각종 뷰들)

		btn_map = (View) findViewById(R.id.btn_map);
		banner_remove = (View) findViewById(R.id.banner_remove);

		menu_more = (LinearLayout) findViewById(R.id.menu_more);
		popup_me = (View) findViewById(R.id.popup_me);
		gomylocation = (View) findViewById(R.id.gomylocation);
		bannerlayout = (FrameLayout) findViewById(R.id.bannerlayout);

		// //////////////////////////////////////////////////////////// (뉴스피드)

		refreshPosition();

		// //////////////////////////////////////////////////////////////////(리스너들)

		banner_remove.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				bannerlayout.setVisibility(View.INVISIBLE);

			}
		});

		popup_me.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent;
				intent = new Intent(getApplicationContext(), MeActivity.class);
				startActivity(intent);

			}
		});

		gomylocation.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				LatLng Point = new LatLng(mylatitude, mylongitude);

				mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Point,
						14));

			}
		});

		getfrommap.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				refreshPosition();
				Intent intent;
				intent = new Intent(getApplicationContext(), ListActivity.class);
				intent.putExtra("isMap", true);
				startActivityForResult(intent, 1);
			}

		});

		gotoplace.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (gotoplace_select.getVisibility() == LinearLayout.GONE) {
					gotoplace_select.setVisibility(LinearLayout.VISIBLE);
				} else {
					gotoplace_select.setVisibility(LinearLayout.GONE);
				}

			}

		});
		place_ex1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				LatLng goPoint = new LatLng(36.5, 127.8);
				mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
						goPoint, 7));
				gotoplace_select.setVisibility(View.GONE);

			}
		});

		place_ex2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				LatLng goPoint = new LatLng(36.5, 127.8);
				mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
						goPoint, 10));
				gotoplace_select.setVisibility(View.GONE);
			}
		});

		// ///////////////////////////////////////////////////////////////

		mGoogleMap.setOnMapClickListener(new OnMapClickListener() {

			public void onMapClick(LatLng point) {
				refreshPosition();

				if (if_click == 0) {

				} else if (if_click == 1) {

					float event_latitude = (float) point.latitude;
					float event_longitude = (float) point.longitude;

					MakeMarker(2, "이벤트", event_latitude, event_longitude);

					Intent intent;
					intent = new Intent(getApplicationContext(),
							MakeActivity.class);
					intent.putExtra("latitude", event_latitude);
					intent.putExtra("longitude", event_longitude);
					intent.putExtra("if_click", if_click);
					startActivity(intent);

					if_click = 0;

				} else if (if_click == 2) {

					float event_latitude = (float) point.latitude;
					float event_longitude = (float) point.longitude;

					MakeMarker(4, "현수막", event_latitude, event_longitude);

					Intent intent;
					intent = new Intent(getApplicationContext(),
							MakeActivity.class);
					intent.putExtra("latitude", event_latitude);
					intent.putExtra("longitude", event_longitude);
					intent.putExtra("if_click", if_click);
					startActivity(intent);

					if_click = 0;

				}

				// String text = "[단시간 클릭시 이벤트] latitude ="
				// + point.latitude + ", longitude ="
				// + point.longitude;
				// Toast.makeText(getApplicationContext(), text,
				// Toast.LENGTH_LONG)
				// .show();
			}
		});

		mGoogleMap.setOnMapLongClickListener(new OnMapLongClickListener() {

			public void onMapLongClick(LatLng point) {
				refreshPosition();
				// String text = "[장시간 클릭시 이벤트] latitude ="
				// + point.latitude + ", longitude ="
				// + point.longitude;
				// Toast.makeText(getApplicationContext(), text,
				// Toast.LENGTH_LONG)
				// .show();
			}
		});

		mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {

			public void onCameraChange(CameraPosition position) {
				refreshPosition();
				// LatLng point = position.target;
				// String text = "[카메라 이동 이벤트] latitude ="
				// + point.latitude + ", longitude ="
				// + point.longitude;
				// Toast.makeText(getApplicationContext(), text,
				// Toast.LENGTH_LONG)
				// .show();
				zoom2 = mGoogleMap.getCameraPosition().zoom;

				if (zoom1 != zoom2) {
					mGoogleMap.clear();

					if (6 < zoom2 && zoom2 < 8) {

						MarkCity();
					}

					if (8 < zoom2 && zoom2 < 18) {

						MarkNormalEvents();
					}
					
					if (10 < zoom2 && zoom2 < 18) {

						MarkNormalArticles();
					}

					zoom1 = zoom2;

				}
			}
		});

		mGoogleMap.setOnMarkerClickListener(new OnMarkerClickListener() {

			public boolean onMarkerClick(Marker marker) {
				refreshPosition();
				
				
				String compare = marker.getTitle();

				if(compare.equals("이동")) {

					LatLng goPoint = new LatLng(marker.getPosition().latitude,
							marker.getPosition().longitude);
					mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
							goPoint, 9));
				} else if(compare.equals("일반마커")){
					
					
				}
			
				return false;
			}
		});

		btn_make_event.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				mGoogleMap.clear();
				Toast.makeText(getApplicationContext(), "이벤트 추가할 곳을 터치해주세요",
						Toast.LENGTH_LONG).show();
				if_click = 1;

			}

		});

		btn_make_banner.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				mGoogleMap.clear();
				Toast.makeText(getApplicationContext(), "현수막 달 곳을 터치해주세요",
						Toast.LENGTH_LONG).show();

				if_click = 2;

			}

		});
		// /////////////////////////////////////////////////////

	}

	public void MarkCity() {

		MakeMarker(11, "서울", 37.5665350, 126.9779690); // 1:normal, 10:검정,11:빨강,
														// 12:초록

		MakeMarker(12, "경기도", 37.4000000, 127.5183000);

		MakeMarker(11, "대전", 36.3504120, 127.3845480);

		MakeMarker(12, "충청도", 36.622940, 126.9541070);

		MakeMarker(12, "강원도", 37.5228000, 128.3955000);

		MakeMarker(12, "강원도", 37.5228000, 128.3955000);

		MakeMarker(12, "경상도", 36.3959060, 128.9676740);

		MakeMarker(11, "울릉도", 37.5063680, 130.8571540);

		MakeMarker(11, "광주", 35.1595450, 126.8526010);

		MakeMarker(12, "전라도", 35.5564250, 127.1541070);

		MakeMarker(11, "대구", 35.8714350, 128.6014450);

		MakeMarker(11, "부산", 35.1795540, 129.0356420);

		MakeMarker(11, "울산", 35.5383770, 129.2113600);

		MakeMarker(12, "제주도", 33.4996210, 126.5311880);

	}

	public void MarkNormalArticles()
	{
		MarkNormalArticles(1);
	}
	
	public void MarkNormalEvents()
	{
		MarkNormalArticles(2);
	}
	
	public void MarkNormalArticles(int option) {

		// 1:normal, 10:검정,11:빨강, 12:초록
//		Toast toast = Toast.makeText(getBaseContext(), "호출은 됨",
//				Toast.LENGTH_SHORT);
//		toast.show();
		int k=0;
		if(option==2) k=2;
		reports_info = UsingServer.getDataFromServer("report_map", 1, k, false);
		if (reports_info == null)
			return;

//		Toast toast1 = Toast.makeText(getBaseContext(), "NULL도 아님",
//				Toast.LENGTH_SHORT);
//		toast1.show();
//
//		Toast toast2 = Toast.makeText(getBaseContext(),
//				TextChecker.purifyString(reports_info[0][1]),
//				Toast.LENGTH_SHORT);
//		toast2.show();

		for (int i = 0; i < reports_info.length; i++) {
			// if(reports_info[i].length!=13)
			MakeMarker(option, "일반마커", Double.parseDouble(TextChecker
					.purifyString(reports_info[i][1])),
					Double.parseDouble(TextChecker
							.purifyString(reports_info[i][2])));

		}
	}

	// 상단 액션바 아이템 리스너
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case android.R.id.home:

			this.finish();

			break;

		case R.id.item1:

			// mGoogleMap.setMyLocationEnabled (true);
			// LatLng myLocation = new
			// LatLng(mGoogleMap.getMyLocation().getLatitude(),mGoogleMap.getMyLocation().getLongitude());

			Intent intent;
			intent = new Intent(getApplicationContext(), ReportActivity.class);
			startActivity(intent);
			break;

		case R.id.item2:
			if (checkActionBar == 1) {
				menu_more.setVisibility(View.VISIBLE);
				item.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
				checkActionBar = 0;
			} else {
				menu_more.setVisibility(View.INVISIBLE);
				item.setIcon(android.R.drawable.ic_menu_more);

				checkActionBar = 1;
			}

		case R.id.item3:
			break;

		default:
			return false;
		}

		return true;
	}

	// 마커 찍어주는 메소드(말풍선 색깔, 텍스트 , 위도, 경도)
	void MakeMarker(int type, String text, double latitude, double longitude) {

		int balloon = R.drawable.marker_red;

		switch (type) {
		case 1:
			balloon = R.drawable.marker_article_normal;
			break;

		case 2:
			balloon = R.drawable.marker_event;
			break;
		case 3:
		balloon = R.drawable.marker_we;
		break;
		case 4:
			balloon = R.drawable.marker_banner;
			break;


		case 10:
			balloon = R.drawable.marker_black;
			break;
		case 11:
			balloon = R.drawable.marker_red;
			break;
		case 12:
			balloon = R.drawable.marker_green;
			break;

		}

		if (type==1) {
			MarkerOptions optSecond = new MarkerOptions();
			optSecond.position(new LatLng(latitude, longitude));
			optSecond.icon(BitmapDescriptorFactory.fromResource(balloon));
			optSecond.title(text);
			mGoogleMap.addMarker(optSecond);

		}else if(type==2){
			
			MarkerOptions optSecond = new MarkerOptions();
			optSecond.position(new LatLng(latitude, longitude));
			optSecond.icon(BitmapDescriptorFactory.fromResource(balloon));
			optSecond.title("이벤트");
			mGoogleMap.addMarker(optSecond);
			
		}
		else {
		

			MarkerOptions optSecond = new MarkerOptions();
			optSecond.position(new LatLng(latitude, longitude));// 위도 • 경도
			optSecond.icon(BitmapDescriptorFactory
					.fromBitmap(writeTextOnDrawable(balloon, text)));
			optSecond.title("이동");
			mGoogleMap.addMarker(optSecond);
		}

	}

	// 텍스트를 비트맵에 그려주는 메소드
	private Bitmap writeTextOnDrawable(int drawableId, String text) {

		Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId)
				.copy(Bitmap.Config.ARGB_8888, true);

		Paint paint = new Paint();
		paint.setStyle(Style.FILL);
		paint.setColor(Color.WHITE);
		paint.setTextAlign(Align.CENTER);
		paint.setTextSize(25);

		Rect bounds = new Rect();

		paint.getTextBounds(text, 0, text.length(), bounds);

		Typeface typeface = Typeface.createFromAsset(getAssets(),
				"fonts/nanumgothicbold.ttf");
		paint.setTypeface(typeface);

		Canvas canvas = new Canvas(bm);

		if (bm.getWidth() < bounds.width()) {
			paint.setTextSize(19);
			paint.getTextBounds(text, 0, text.length(), bounds);
		}

		if (bm.getWidth() < bounds.width()) {
			paint.setTextSize(15);
			paint.getTextBounds(text, 0, text.length(), bounds);
		}

		canvas.drawText(text, bm.getWidth() / 2, bm.getHeight() / 2, paint);

		return bm;
	}

	public static int convertToPixels(Context context, int nDP) {
		final float conversionScale = context.getResources()
				.getDisplayMetrics().density;

		return (int) ((nDP * conversionScale) + 0.5f);

	}

	// 뉴스피드 관련 어댑터

	// 지도 검색(주소로 위도, 경도값 알아내는) 기능 구현을 위한 메소드

	@SuppressLint("NewApi")
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		getActionBar().setLogo(R.drawable.actionbar_icon2);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setBackgroundDrawable(
				new ColorDrawable(Color.rgb(248, 157, 105)));

		if (option_near_or_all == 0) {
			getActionBar().setTitle("주변 맵 뷰");
		} else if(option_near_or_all == 1) {
			getActionBar().setTitle("전체 맵 뷰");
		}else{
			getActionBar().setTitle("맵 뷰");
		}

		return true;
	}

	public void refreshPosition() {
		for (int i = 0; i < 4; i++) {
			location[i][0] = mGoogleMap.getProjection().fromScreenLocation(
					screenPointForLocation[i]).latitude;
			location[i][1] = mGoogleMap.getProjection().fromScreenLocation(
					screenPointForLocation[i]).longitude;
		}
	}
	
	public void onBackPressed() {

		Toast toast = null;

		if (gotoplace_select.getVisibility()==LinearLayout.VISIBLE) {
			gotoplace_select.setVisibility(LinearLayout.GONE);
			

		} else {
this.finish();
		
		}
	}
}
